import sys

def build(bld):
    bdist_base = bld.path.get_bld().make_node('build')
    dist_dir = bld.path.get_bld().make_node('dist')

    pdc_gen = bld.path.find_node('../generate_pdcs/pdc_gen.py')
    image_routines = bld.path.find_node('../pebble_image_routines.py')
    pbi2png_script = bld.path.find_node('../pbi2png.py')
    setup = bld.path.find_node('setup.py')
    pdc2png = bld.path.get_bld().parent.parent.make_node('pdc2png')

    def py2app(task):
        template = "python {} py2app --bdist-base={} --dist-dir={} --extra-scripts={},{},{} --packages=PIL,ctypes"
        ctx = task.generator.bld
        try:
            ctx.cmd_and_log(template.format(task.inputs[0].abspath(), 
                                            task.outputs[0].abspath(), 
                                            task.outputs[1].abspath(),
                                            task.inputs[1].abspath(),
                                            task.inputs[2].abspath(),
                                            task.inputs[3].abspath()))
        except Exception as e:
            # catch macholib bug and give user the diff to fix it
            if e.stderr.find("dyld_find() got an unexpected keyword argument 'loader'") > 0:
                raise Exception("You have a bugged version of macholib. Until it's updated, apply the following patch:\n"
                                "--- a/usr/local/lib/python2.7/site-packages/macholib/MachOGraph.py\n"
                                "+++ a/usr/local/lib/python2.7/site-packages/macholib/MachOGraph.py\n"
                                "@@ -46,7 +46,7 @@ class MachOGraph(ObjectGraph):\n"
                                "                 try:\n"
                                "                     fn = dyld_find(filename, env=self.env,\n"
                                "                         executable_path=self.executable_path,\n"
                                "-                        loader=loader.filename)\n"
                                "+                        loader_path=loader.filename)\n"
                                "                     self.trans_table[(loader.filename, filename)] = fn\n"
                                "                 except ValueError:\n"
                                "                     return None\n\n"
                                )
            else:
                raise Exception(e)




    bld(name='py2app', 
        rule=py2app, 
        source=[setup, pdc_gen, image_routines, pbi2png_script],
        target=[bdist_base, dist_dir])


    app = dist_dir.make_node('/svg2png.app')
    pdc2png_copy = dist_dir.make_node('/svg2png.app/Contents/Resources').make_node('pdc2png')
    bld(rule="cp ${SRC} ${TGT}", source=pdc2png, target=pdc2png_copy, after='py2app')

# vim:filetype=python
